
package com.wy2cloud.authorize.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wy2cloud.authorize.util.HttpServletUtils;
import com.wy2cloud.authorize.util.ProxyPrefixHttpServletRequestWrapper;

/**
 * 服务相对于服务网关 前缀路径处理过滤器
 * @author wuyy<16349023@qq.com>,nnsword
 * @date 2018年3月20日下午5:37:36
 *
 */
public class PrefixPathHandleFilter implements Filter {
	
	private final static Logger logger=LoggerFactory.getLogger(PrefixPathHandleFilter.class);
	
    /**
     * 默认Order
     */
    public static final int DEFAULT_ORDER = Integer.MAX_VALUE -100;

    public static final String ATTR_NAME="prefixPath";
    private static final String Default_Context_Path="/";

    public static final String getPrefixPath(HttpServletRequest request){
        Object obj=  request.getAttribute(PrefixPathHandleFilter.ATTR_NAME);
        String prefixPath="";
        if(obj!=null){
            prefixPath=(String) obj;
        }
        return prefixPath;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        
        Object oPrefix=req.getAttribute(ATTR_NAME);
        if(oPrefix==null) {
            String contextPath=req.getContextPath();
            
            //取zuul下发的proxy-header信息
            String prefixPath= HttpServletUtils.getZuulPrefix(req,false);
            if(prefixPath == null){
                prefixPath="";
            }
            if(!Default_Context_Path.equals(contextPath)){
                prefixPath+=contextPath;
            }
            req.setAttribute(ATTR_NAME,prefixPath);
            
            request = new ProxyPrefixHttpServletRequestWrapper(req);
            
        }

        chain.doFilter(request, response);

        logger.info("内容路径：{} \n {} \n {}",((HttpServletRequest)request).getContextPath(), ((HttpServletRequest)request).getPathInfo()
        		, ((HttpServletRequest)request).getServletPath());
    }

    @Override
    public void destroy() {

    }


}